package com.lxl.bt.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lxl.bt.Constant;
import com.lxl.bt.R;
import com.lxl.bt.bean.A_Login;
import com.lxl.bt.bean.AppVersionBean;
import com.lxl.bt.bean.LogoutMessage;
import com.lxl.bt.fragment.FindFragment;
import com.lxl.bt.fragment.HomeFragment;
import com.lxl.bt.fragment.MyFragment;
import com.lxl.bt.fragment.WaKuangFragment;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.lxl.bt.util.DownloadUtils;
import com.lxl.bt.util.Prefs;
import com.yanzhenjie.sofia.Sofia;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by lvxinlong
 * on 首页
 **/
public class HomeActivity extends BaseActivity {


    @BindView(R.id.flMain)
    FrameLayout flMain;
    @BindView(R.id.ivF1)
    ImageView ivF1;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.lin1)
    LinearLayout lin1;
    @BindView(R.id.ivF2)
    ImageView ivF2;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.lin2)
    LinearLayout lin2;
    @BindView(R.id.ivF3)
    ImageView ivF3;
    @BindView(R.id.lin3)
    LinearLayout lin3;
    @BindView(R.id.lin_bottom_bar)
    LinearLayout linBottomBar;
    @BindView(R.id.vb)
    View vb;
    @BindView(R.id.ivF4)
    ImageView ivF4;
    @BindView(R.id.lin4)
    LinearLayout lin4;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.tv4)
    TextView tv4;
    private Context context;


    private ArrayList<Fragment> mFragments = new ArrayList<>();
    ACache aCache;
    private Fragment[] fragments;
    public static int lastShowFragment = 0;
    A_Login a_login;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        StatusBarUtils.fullScreen(this);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        //状态栏全透明全屏显示页面，布局能够延伸到状态栏和导航栏下方
//        Sofia.with(this)
//                .invasionStatusBar()
//                .statusBarDarkFont()
//                .statusBarBackgroundAlpha(0)
////                .invasionNavigationBar()
//                .navigationBarBackgroundAlpha(0);

//                .setDrawable(getResources().getDrawable(R.drawable.shape))

        context = this;

        aCache = ACache.get(this);

        removeAllFragment();
        initFragments();
        queryAppVersion();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        a_login= (A_Login) aCache.getAsObject(Constant.LOGIN);
//        if(a_login==null){
//            startActivity(new Intent(this, LoginActivity.class));
//            finish();
//        }
        needLogin();
        initBottom(lastShowFragment);
        switchFrament(lastShowFragment, lastShowFragment);
        linBottomBar.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (lastShowFragment == 2) {
                    Sofia.with(HomeActivity.this)
                            .invasionStatusBar()
                            .statusBarBackgroundAlpha(0)
//                        .statusBarLightFont();
                            .statusBarDarkFont()
                            .invasionNavigationBar()
                            .navigationBarBackgroundAlpha(0)
//                        .fitsNavigationBarView(linBottomBar)
                    ;
                } else {
                    Sofia.with(HomeActivity.this)
                            .invasionStatusBar()
                            .statusBarBackgroundAlpha(0)
                            .statusBarLightFont()
                            .invasionNavigationBar()
                            .navigationBarBackgroundAlpha(0);
                }
            }
        }, 500);
    }

    private int getAppLocationVersionCode(){
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return Integer.MAX_VALUE;
    }

    private void queryAppVersion(){
        RetrofitUtil.getInstance().create(NetApi.class,1).queryAppVersion(0).enqueue(new NetCallback<Result<AppVersionBean>>() {
            @Override
            public void onSuccess(Result<AppVersionBean> result) {
                AppVersionBean data = result.getData();
                int appLocationVersionCode = getAppLocationVersionCode();
                if (data.androidVersion > appLocationVersionCode){
                    //服务器版本大于本地版本，需要更新
                    //显示更新弹框
                    showUpdateAppDialog(data.androidMsg,data.isUpgrade == 0,data.androidUrl,data.androidVersion);
                }
            }

            @Override
            public void netLogin() {

            }
        });
    }

    private void showUpdateAppDialog(String message,boolean forceUpdate,String url,int version){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("APP升级");
        builder.setMessage(message);
        builder.setPositiveButton("立即升级", (dialog, which) -> {
            //下载APP并安装
            String appName = "yueqilin_" +  version + ".apk";
            new DownloadUtils(context, url, appName);
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.setCanceledOnTouchOutside(!forceUpdate);
        alertDialog.setCancelable(!forceUpdate);

        alertDialog.show();
    }

    private void needLogin() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .tokenIsValid(Prefs.getStringValue(Constant.JSESSIONID)).enqueue(new NetCallback<Result<Boolean>>() {
            @Override
            public void onSuccess(Result<Boolean> result) {
                if (result.isSuccess()&&result.getData()) {

                }else{
                    startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                    finish();
                }
            }

            @Override
            public void netLogin() {
                startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                finish();
            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", ">>>>>" + errorStr);
                startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                finish();
            }

        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    private void initBottom(int w) {

        ivF1.setImageResource(R.mipmap.home);
        ivF2.setImageResource(R.mipmap.wakuang);
        ivF3.setImageResource(R.mipmap.find);
        ivF4.setImageResource(R.mipmap.mine);
        tv1.setTextColor(getResources().getColor(R.color.color_text_gray));
        tv2.setTextColor(getResources().getColor(R.color.color_text_gray));
        tv3.setTextColor(getResources().getColor(R.color.color_text_gray));
        tv4.setTextColor(getResources().getColor(R.color.color_text_gray));
        switch (w) {
            case 0:
                ivF1.setImageResource(R.mipmap.homeed);
                tv1.setTextColor(getResources().getColor(R.color.colorMain));
                Sofia.with(this)
                        .invasionStatusBar()
                        .statusBarBackgroundAlpha(0)
                        .statusBarLightFont()
                        .invasionNavigationBar()
                        .navigationBarBackgroundAlpha(0)
//                        .fitsNavigationBarView(linBottomBar)
                ;
//                .statusBarDarkFont()
                break;
            case 1:
                ivF2.setImageResource(R.mipmap.wakuanged);
                tv2.setTextColor(getResources().getColor(R.color.colorMain));
                Sofia.with(this)
                        .invasionStatusBar()
                        .statusBarBackgroundAlpha(0)
                        .statusBarLightFont()
                        .invasionNavigationBar()
                        .navigationBarBackgroundAlpha(0)
//                        .fitsNavigationBarView(linBottomBar)
                ;
//                .statusBarDarkFont()
                break;
            case 2:
                tv3.setTextColor(getResources().getColor(R.color.colorMain));
                ivF3.setImageResource(R.mipmap.finded);
                Sofia.with(this)
                        .invasionStatusBar()
                        .statusBarBackgroundAlpha(0)
//                        .statusBarLightFont();
                        .statusBarDarkFont()
                        .invasionNavigationBar()
                        .navigationBarBackgroundAlpha(0)
//                        .fitsNavigationBarView(linBottomBar)
                ;
                break;
            case 3:
                tv4.setTextColor(getResources().getColor(R.color.colorMain));
                ivF4.setImageResource(R.mipmap.mineed);
                Sofia.with(this)
                        .invasionStatusBar()
                        .statusBarBackgroundAlpha(0)
//                        .statusBarLightFont();
                        .statusBarDarkFont()
                        .invasionNavigationBar()
                        .navigationBarBackgroundAlpha(0)
//                        .fitsNavigationBarView(linBottomBar)
                ;
                break;
        }

    }

    private void initFragments() {
        fragments = new Fragment[]{HomeFragment.newInstance(), WaKuangFragment.newInstance(), FindFragment.newInstance(), MyFragment.newInstance()};
        switchFrament(lastShowFragment, lastShowFragment);
    }

    public void switchFrament(int lastIndex, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (lastIndex != index)
            transaction.hide(fragments[lastIndex]);
//        if (!fragments[index].isAdded() && null == getSupportFragmentManager().findFragmentByTag(index + "")) {
        if (!fragments[index].isAdded()) {
            transaction.add(R.id.flMain, fragments[index], index + "");
        } else {
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
        lastShowFragment = index;
    }

    private void removeAllFragment() {
        FragmentTransaction begin = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < 4; i++) {
            Fragment f = getSupportFragmentManager().findFragmentByTag(i + "");
            if (f != null && f.isAdded()) {
                begin.remove(f);
            }
        }
        begin.commit();
    }

    @OnClick({R.id.lin1, R.id.lin2, R.id.lin3, R.id.lin4})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lin1:
                initBottom(0);
                switchFrament(lastShowFragment, 0);
                break;
            case R.id.lin2:
                initBottom(1);
//                requestPermission();
                switchFrament(lastShowFragment, 1);
                break;
            case R.id.lin3:
                initBottom(2);
                switchFrament(lastShowFragment, 2);
                break;
            case R.id.lin4:
                initBottom(3);
                switchFrament(lastShowFragment, 3);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(LogoutMessage message) {
        startActivity(new Intent(HomeActivity.this, LoginActivity.class));
    }
}
